const path = require('path');
const fs = require('fs');
const db = require("./sqlitedb.js");


//获取轮播图文件夹下的图片名称
function getswipeimage(path){
    let files = fs.readdirSync(path);
    let imgarr = [];
    files.forEach((item,index)=>{
        imgarr.push(item);
    })
    return imgarr;
}
exports.getswiptimg = (req,res)=>{
    var id = 0;
    var images = getswipeimage(path.join(__dirname,"../public/images"))
    var new_images = images.map((item)=>{
        id++;
        var obj = {};
        obj.path = "http://localhost:3000/image/"+item;
        // obj.id = Date.now();
        obj.id = id;
        return obj;
    })
    res.header('Access-Control-Allow-Origin', '*');
    res.json(new_images);
}
exports.getsqlinfo = (req,res)=>{
    db.getinfo("select * from SWIPEIMG").then(function(data){
        res.header('Access-Control-Allow-Origin','*');
        var newdata = data.map((item)=>{
            var obj = {};
            obj.id = item.id;
            obj.title = item.title;
            obj.img = "http://localhost:3000/news/images/"+ item.img;
            obj.txt = fs.readFileSync(path.join(__dirname,"../public/news/info/"+item.txt),'utf8')
            return obj;
        })
        res.json(newdata)
    },function(err){
        res.header('Access-Control-Allow-Origin', '*');
        res.json(err)
    })
}
exports.setsqlinfo = (req,res)=>{//上传新闻图片数据到数据库
    var obj = req.body;
    var title = obj.title;
    var img = obj.img;
    var txt = obj.txt;
    db.setinfo(`INSERT INTO SWIPEIMG(title,img,txt) values('${title}','${img}','${txt}')`).then(function(data){
        res.header('Access-Control-Allow-Origin', '*');
        res.json('数据上传成功')
    },function(err){
        res.header('Access-Control-Allow-Origin', '*');
        res.json(err)
    })
}
exports.setCmtIfo = (req,res) =>{

}
exports.imagesupload = (req,res)=>{
    let {buffer,mimetype} = req.file;
    let fileName = (new Date()).getTime() + parseInt(Math.random()*3435) + parseInt(Math.random()*6575);
    let fileType = mimetype.split('/')[1];
    let apath = `http://localhost:3000/news/images/${fileName}.${fileType}`;
    fs.writeFile(path.join(__dirname,`../public/news/images/${fileName}.${fileType}`),buffer,"utf8",(data)=>{
        if(data){
            res.header('Access-Control-Allow-Origin', '*');
            res.send(data);
        }else{
            res.header('Access-Control-Allow-Origin', '*');
            res.send([apath,`${fileName}.${fileType}`]);//返回地址和文件名称
        }
    })
}
//用于新闻内容上传
exports.txtupload = (req,res)=>{
    var title = req.body.title;//传输的标题
    var container = req.body.container;//传输的内容
    let fileName = (new Date()).getTime() + parseInt(Math.random()*3435) + parseInt(Math.random()*6575);
    let apath = `http://localhost:3000/news/info/${fileName}.txt`;
    fs.writeFile(path.join(__dirname,`../public/news/info/${fileName}.txt`),title+container,"utf8",(err)=>{
        if(err){
            res.header('Access-Control-Allow-Origin', '*');
            res.send("文本上传失败");
        }else{
            res.header('Access-Control-Allow-Origin', '*');
            res.send([apath,fileName+'.txt']);//返回地址和文件名称
        }
    })

}
//用于图片内容描述上传为txt文档
exports.ImgDescUpload = (req,res)=>{
    let imginfo = req.body;//传输的内容
    let filename = "img_"+(new Date()).getTime() + parseInt(Math.random()*3435) + parseInt(Math.random()*6575);
    let apath = `http://localhost:300/news/info/${filename}.txt`
    fs.writeFile(path.join(__dirname,`../public/news/info/${filename}.txt`),imginfo.imgdesc,'utf8',(err)=>{
        if(err){
            res.header('Access-Control-Allow-Origin', '*');
            res.json('图片信息上传失败');
        }else{
            res.header('Access-Control-Allow-Origin', '*');
            res.json([apath,filename+'.txt']);
        }
    })
}
//上传图片游览的数据到指定的数据库
exports.SetImgInfoSql = (req,res)=>{
    let obj = req.body;
    let title = obj.title;
    let img = obj.img;
    let txt = obj.txt;
    let time = obj.time;
    let type = obj.type;
    db.setinfo(`INSERT INTO IMGDESCINFO (type,title,img,txt,time) VALUES('${type}','${title}','${img}','${txt}','${time}')`).then(function(data){
        res.header('Access-Control-Allow-Origin','*');
        res.json(data);
    })
}
//获取图文展示列表值(所有值)
exports.GetImgInfo_List = (req,res)=>{
    db.getinfo("SELECT * FROM IMGDESCINFO").then(function(data){
        res.header('Access-Control-Allow-Origin', '*');
        var newarr = data.map((item)=>{
            var obj = {};
            obj.id = item.id;
            obj.type = item.type;
            obj.title = item.title;
            obj.img = "http://localhost:3000/news/images/"+ item.img;
            obj.txt = item.txt;
            try{
                obj.infoall = fs.readFileSync(path.join(__dirname,"../public/news/info/"+item.txt),'utf8');
            }catch{
                obj.infoall = "文章已丢失";
            }           
            obj.time = item.time;
            return obj;
        })
        res.json(newarr)
    },function(err){
        res.header('Access-Control-Allow-Origin', '*');
        res.json(err)
    })
}
//获取图文类别
exports.GetImgInfoType = (req,res)=>{
    db.getinfo("SELECT DISTINCT(type) FROM IMGDESCINFO").then((result)=>{
        res.header('Access-Control-Allow-Origin', '*');
        var newarr = result.map((item)=>{
            item.id = parseInt(Math.random()*875221464);
            return item;
        })
        res.json(newarr);
    },(err)=>{
        res.header('Access-Control-Allow-Origin', '*');
        res.json(err)
    })
}
//根据类别获取列表值
exports.GetImgInfo_List_Type = (req,res)=>{
    let type = req.params.type;
    db.getinfo(`SELECT * FROM IMGDESCINFO where type = '${type}'`).then((result)=>{
        res.header('Access-Control-Allow-Origin', '*');
        var newarr = result.map((item)=>{
            var obj = {};
            obj.id = item.id;
            obj.title = item.title;
            obj.img = "http://localhost:3000/news/images/"+ item.img;
            obj.txt = item.txt;
            obj.infoall = fs.readFileSync(path.join(__dirname,"../public/news/info/"+item.txt),'utf8')
            obj.time = item.time;
            return obj;
        })
        res.json(newarr)
    },(err)=>{
        res.header('Access-Control-Allow-Origin', '*');
        res.json(err)
    })
}
//根据id值获取详细图文信息和评论
exports.GetImgInfoById = (req,res)=>{
    db.getinfo(`SELECT * FROM IMGDESCINFO WHERE id = '${req.params.id}'`).then(function(data){
        res.header('Access-Control-Allow-Origin', '*');
        var item = data[0];
        var obj = {};
        obj.id = item.id;
        obj.img = "http://localhost:3000/news/images/"+ item.img;
        obj.infoall = fs.readFileSync(path.join(__dirname,"../public/news/info/"+item.txt),'utf8')
        obj.time = item.time;
        res.json(obj)
    },function(err){
        res.header('Access-Control-Allow-Origin', '*');
        res.json(err)
    })
}
//用于评论内容上传
exports.CmtUpload = (req,res)=>{
    var obj = req.body;//获取POST传输数据
    db.addCmtItem(obj).then(function(data){
        res.header('Access-Control-Allow-Origin', '*');
        res.send(data);
    })
}
//用于评论内容展示
exports.ShowCmt = (req,res)=>{
    var obj = req.body;//获取POST传输数据
    db.showCmtList(obj).then(function(data){
        res.header('Access-Control-Allow-Origin', '*');
        res.send(data);
    })
}